﻿/// <reference path="db_define_construct1.js" />
var net = require('net');
var url = require('url');
var crc16 = require('./crc.js');
var server_post = require('./server_post');
var udp = require('./udpserver.js');

//var aaafun = require("./test.js");
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//写sensor传感器的指令保存
var read_col_cycle = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x31, 0x00, 0x01, 0xb7, 0x84, 0x16];     //读取采集间隔时间
var read_signal = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x58, 0x00, 0x01, 0x67, 0x98, 0x16];     //读取信号强度 ]
var read_mobile = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x59, 0x00, 0x03, 0xb7, 0x99, 0x16];     //手机号码
var read_punit = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x32, 0x00, 0x01, 0x47, 0x84, 0x16];     //读取压力单位
var read_lvalue = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x34, 0x00, 0x02, 0xe7, 0x84, 0x16];     //读取最小量程
var read_bvalue = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x36, 0x00, 0x02, 0x46, 0x44, 0x16];     //读取最大量程
var read_down = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x50, 0x00, 0x02, 0xa6, 0x5b, 0x16];     //读取报警下限
var read_up = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x52, 0x00, 0x02, 0x07, 0x9b, 0x16];     //读取报警上限 ]
var read_vol = [0x69, 0x00, 0x01, 0x00, 0x01, 0x03, 0x00, 0x54, 0x00, 0x02, 0xE7, 0x9A, 0x16];     //读取电池电压 
var read_info_all = [read_col_cycle, read_signal, read_mobile, read_punit, read_lvalue, read_bvalue, read_down, read_up, read_vol];
var read_info = {
    "col_cycle": read_col_cycle
    , "signal": read_signal
    , "mobile": read_mobile
    , "punit": read_punit
    , "lvalue": read_lvalue
    , "bvalue": read_bvalue
    , "down": read_down
    , "up": read_up
    , "vol": read_vol
};


var write1_col_cycle = [0x69, 0x00, 0x01, 0x00, 0x01, 0x06, 0x00, 0x31, 0x00, 0x32, 0x3b, 0x91, 0x16];    //写入采集间隔时间50S   ok 
//69 00 01 00 01 06 00 31 00 32 3B 91 16    //指令原样回传 
var write_warn_down = [0x69, 0x00, 0x01, 0x00, 0x01, 0x10, 0x00, 0x50, 0x00, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x67, 0x16];   //修改报警下限  0   OK
//69 00 01 00 01 10 00 50 00 02 23 98 16                  //报警下限回传指令  
var write_warn_up = [0x69, 0x00, 0x01, 0x00, 0x01, 0x10, 0x00, 0x52, 0x00, 0x02, 0x04, 0x44, 0x7A, 0x00, 0x00, 0xaf, 0x97, 0x16];   //修改报警上限  1000  OK
//69 00 01 00 01 10 00 52 00 02 82 58 16                  //报警下限回传指令 
var write_AH_AL = [0x69, 0x00, 0x01, 0x00, 0x01, 0x06, 0x00, 0x54, 0x00, 0x00, 0xaa, 0x5b, 0x16];//    //保存AH  AL  报警上限下限参数 OK
//69 00 01 00 01 06 00 54 00 01 6B 9B 16    //指令原样回传 
var write_phone = [0x69, 0x00, 0x01, 0x00, 0x01, 0x10, 0x00, 0x40, 0x00, 0x06, 0x0C, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x64, 0xE1, 0x16];

var deviceid_socket = {};

function Str2Bytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
        return null;
    }
    len /= 2;
    var hexA = new Array();
    for (var i = 0; i < len; i++) {
        var s = str.substr(pos, 2);
        var v = parseInt(s, 16);
        hexA.push(v);
        pos += 2;
    }
    return hexA;
}

function setdeviceid(id, buf_target) {
    //id传入的是字符串
    var x = Str2Bytes(id);
    var bx = Buffer.from(x);
    bx.copy(buf_target, 1, 0, 4);
}
function setcrc16(buf_target) {
    var len = buf_target.length;
    if (len < 5)
        return false;
    var copybuf = [];
    for (var i = 0; i < len - 3 ; i++) {
        copybuf.push(buf_target[i]);
    }
    var ret = crc16.GetCrc16(copybuf);
    var hiret = ret >> 8;
    var loret = ret & 0xff;
    //低字节赋值
    buf_target[len - 1 - 1] = loret;
    //高字节赋值
    buf_target[len - 1 - 2] = hiret;
}

function send_Read_infoAll(num, id, socket) {
    var data = read_info_all[num];
    if (data == null) {
        console.log("error!no flag of %s", flag);
        return;
    }
    var buf_temp = Buffer.from(data);

    setdeviceid(id, buf_temp);
    setcrc16(buf_temp);
    socket.write(buf_temp);
}

function sendWrite(id, flag, v, socket) {
    var buf_temp;
    var v_temp;
    if (flag == "col_cycle") {
        buf_temp = Buffer.from(write1_col_cycle);
        v_temp = parseInt(v);
        buf_temp.writeInt16BE(v_temp, 8);
    }
    else if (flag == "warn_up") {
        buf_temp = Buffer.from(write_warn_up);
        v_temp = parseFloat(v);
        buf_temp.writeFloatBE(v_temp, 11);
    }
    else if (flag == "warn_down") {
        buf_temp = Buffer.from(write_warn_down);
        v_temp = parseFloat(v);
        buf_temp.writeFloatBE(v_temp, 11);
    }
    else if (flag == "phonenumber1") {
        buf_temp = Buffer.from(write_phone);
        buf_temp[11] = 0x00;
        for (var i = 0; i < 11; i++) {
            //从12字节开始是电话号码
            buf_temp[i + 12] = v.charAt(i);
        }
    }
    else if (flag == "phonenumber2") {
        buf_temp = Buffer.from(write_phone);
        buf_temp[11] = 0x01;
        for (var i = 0; i < 11; i++) {
            //从12字节开始是电话号码
            buf_temp[i + 12] = v.charAt(i);
        }
    }
    else if (flag == "phonenumber3") {
        buf_temp = Buffer.from(write_phone);
        buf_temp[11] = 0x02;
        for (var i = 0; i < 11; i++) {
            //从12字节开始是电话号码
            buf_temp[i + 12] = v.charAt(i);
        }
    }
    else if (flag == "phonenumber4") {
        buf_temp = Buffer.from(write_phone);
        buf_temp[11] = 0x03;
        for (var i = 0; i < 11; i++) {
            //从12字节开始是电话号码
            buf_temp[i + 12] = v.charAt(i);
        }
    }
    else if (flag == "phonenumber5") {
        buf_temp = Buffer.from(write_phone);
        buf_temp[11] = 0x04;
        for (var i = 0; i < 11; i++) {
            //从12字节开始是电话号码
            buf_temp[i + 12] = v.charAt(i);
        }
    }
    else if (flag == "alahsave") {
        buf_temp = Buffer.from(write_AH_AL)
    }
    else {
        console.log("command is error");
        return;
    }
    setdeviceid(id, buf_temp);
    //设置crc16
    setcrc16(buf_temp);
    socket.write(buf_temp);
}
//st数组 len是数组的长度
function time_func_write(st, len, deviceid, socket) {
    var interval = 500;
    //read_time++;
    var t = len - 1;
    if (t == -1)
        return;
    setTimeout(function () {
        sendWrite(deviceid, st[t].flag, st[t].value, socket);
        time_func_write(st, t, deviceid, socket);
    }, interval);//
}
function time_func_write2(st, pos, len, deviceid, socket) {
    var interval = 1000;
    //read_time++;
    pos++;
    if (pos == len + 1)
        return;
    setTimeout(function () {
        sendWrite(deviceid, st[pos - 1].flag, st[pos - 1].value, socket);
        time_func_write2(st, pos, len, deviceid, socket);
    }, interval);//
}
function send2Sensor_write0(data) {
    var obj = deviceid_socket[data.deviceid];
    if (obj == null)
        return;
    var socket = obj.sock;
    if (socket == null) {
        console.log("not online deviceid %s", data.deviceid);
        return;
    }
    //保存所有的写命令
    obj.data = data;

}
function send2Sensor_write(data) {

    var st = [];
    if (data.deviceid == null || data.deviceid == "") {
        return;
    }
    //console.log("send2Sensor:");
    var obj = deviceid_socket[data.deviceid];
    if (obj == null)
        return;
    var socket = obj.sock;
    if (socket == null) {
        console.log("not online deviceid %s", data.deviceid);
        return;
    }
    //保存所有的写命令
    obj.data = data;
    //obj.time = new Date().getTime();
    obj.nwrite = 0; //要写的数据的个数
    obj.nwrite_ret = 0; //写数据回送了几次
    if (obj.online == 0) {
        console.log("not on line %s", data.deviceid);
        return;
    }
    //id是字符串
    //st.id = data.deviceid;
    //var timeout = 500;
    if (data.col_cycle != null) {
        obj.nwrite++; //要写的数据的个数
        var o1 = {};
        //o1.id = data.deviceid;
        o1.flag = "col_cycle";
        o1.value = data.col_cycle;
        //o1.sock = socket;
        st.push(o1);
    }

    var sendah = false;
    if (data.warn_up != null && data.warn_up != "") {
        obj.nwrite++; //要写的数据的个数
        sendah = true;
        var o = {};
        o.flag = "warn_up";
        o.value = data.warn_up;
        st.push(o);
    }
    if (data.warn_down != null && data.warn_down != null) {
        sendah = true;
        obj.nwrite++; //要写的数据的个数
        var o = {};
        o.flag = "warn_down";
        o.value = data.warn_down;
        st.push(o);
    }
    // sendah = false; //这里要去掉
    if (sendah == true) {
        obj.nwrite++; //要写的数据的个数
        var o = {};
        o.flag = "alahsave";
        o.value = 0;//data.warn_up;
        st.push(o);
    }
    if (data.phonenumber1 != null) {
        var str = "";
        str += data.phonenumber1;
        if (str.length < 11) {
            console.log("error phonenumber1 is not right!:%s", str);
        }
        else {

            console.log("the phone number is %s %d", str, str.length);
            obj.nwrite++; //要写的数据的个数
            var o = {};
            o.flag = "phonenumber1";
            o.value = str;
            st.push(o);
        }
    }
    if (data.phonenumber2 != null) {
        var str = "";
        str += data.phonenumber2;
        if (str.length < 11) {
            console.log("error phonenumber1 is not right!:%s", str);
        }
        else {
            obj.nwrite++; //要写的数据的个数
            var o = {};
            o.flag = "phonenumber2";
            o.value = str;
            st.push(o);
        }
    }
    if (data.phonenumber3 != null) {
        var str = "";
        str += data.phonenumber3;
        if (str.length < 11) {
            console.log("error phonenumber1 is not right!:%s", str);
        }
        else {
            obj.nwrite++; //要写的数据的个数
            var o = {};
            o.flag = "phonenumber3";
            o.value = str;
            st.push(o);
        }
    }
    if (data.phonenumber4 != null) {
        var str = "";
        str += data.phonenumber4;
        if (str.length < 11) {
            console.log("error phonenumber1 is not right!:%s", data.phonenumber4);
        }
        else {
            obj.nwrite++; //要写的数据的个数
            var o = {};
            o.flag = "phonenumber4";
            o.value = str;
            st.push(o);
        }
    }
    if (data.phonenumber5 != null) {
        var str = "";
        str += data.phonenumber5;
        if (str.length < 11) {
            console.log("error phonenumber1 is not right!:%s", str);
        }
        else {
            obj.nwrite++; //要写的数据的个数
            var o = {};
            o.flag = "phonenumber5";
            o.value = str;
            st.push(o);
        }
    }
    time_func_write2(st, 0, st.length, data.deviceid, socket);
}
function time_func_ask(deviceid, socket, readtime) {
    var interval = 500;
    //read_time++;
    setTimeout(function () {
        send_Read_infoAll(readtime, deviceid, socket);
        var xread = readtime - 1;
        if (xread == -1)
            return;
        time_func_ask(deviceid, socket, xread);
    }, interval);//
}
function send2sensor_ask(deviceid) {
    if (deviceid == null) {
        return;
    }
    //var deviceid = data.deviceid;

    var obj = deviceid_socket[deviceid];
    if (obj == null) {
        console.log("no socket here");
        return;
    }

    if (obj.online == 1) { //在线
        console.log("ask the data");
        time_func_ask(deviceid, obj.sock, 8);
    }
}

function ProcessTcpServer(callback) {
    var server = net.createServer();
    //接受新的客户端连接  
    server.on('connection', function (socket) {
        //socket.manager.transports[socket.id].socket.setTimeout(25000);
        var v_deviceid = null;
        var port = socket.remotePort;
        var addr = socket.remoteAddress;

        console.log('CONNECTED: ' + socket.remoteAddress + ':' + socket.remotePort);
        //sockets.push(socket);
        //缓冲区 512字节
        const buf = Buffer.allocUnsafe(512);
        //缓存中的数据长度
        var buf_datasize = 0;

        //得到保存的对象
        function sock_obj() {
            if (v_deviceid == null)
                return null;
            return deviceid_socket[v_deviceid];
        }
        //69 00 01 00 01 04 08 46 7A 0B E8 41 F1 00 00 B2 87 16      // 压力16000  +  温度30.1 
        function device_offline() { //设备下线
            if (v_deviceid != null) {
                if (callback != null)
                    callback(null,{ deviceid: v_deviceid, status: 0 });
                var obj = sock_obj();
                if (obj != null)
                    obj.online = 0;
            }
        }
        function device_online() {
            if (v_deviceid != null) {
                if (callback != null)
                    callback(null, { deviceid: v_deviceid, status: 1 });
                var obj = sock_obj();
                if (obj != null)
                    obj.online = 0;
            }
        }
        function process_packet_cmd04(buff, pos, len) {
            //注意toString 1-5,是取四个字节
            v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            //console.log(buff);
            var v_press = buff.readFloatBE(pos + 7);
            v_press = v_press.toFixed(1);
            var v_temp = buff.readFloatBE(pos + 11);
            v_temp = v_temp.toFixed(1);
            var v_extern = null; //扩展8字节
            if (len - 10 == 0x10){ //后面还有扩展字节 2017/10/23日,减去头部尾部10字节，剩余16字节
            
                var e_vol = buff.readFloatBE(pos+15);//电压 四字节
                e_vol = e_vol.toFixed(1);//保留1字节
                var e_ct = buff.readInt16BE(pos+19);////采集时间 两个字节
                var e_sn  = buff[21];//信号强度 1字节
                var npa   = buff[22];//压力单位 00 pa 01 Hpa 02 Kpa 03 Mpa  1字节
                var e_pa = "pa";
                if (npa == 0)
                    e_pa = "pa";
                else if (npa == 1)
                    e_pa = "Hpa";
                else if (npa == 2)
                    e_pa = "Kpa";
                else if (npa == 3)
                    e_pa = "Mpa";
                v_extern = { vol: e_vol, col_cycle: e_ct, signal: e_sn, press_unit: e_pa };
            }
            device_online();
            //sock保存，是否在线，data，需要写的数据是否存在
            var obj = deviceid_socket[v_deviceid];


            if (obj == null) {
                deviceid_socket[v_deviceid] = {
                    sock: socket,
                    deviceid: v_deviceid,
                    online: 1,
                    data: null,
                    nwrite: 0,      //要写的数据的个数
                    nwrite_ret: 0, //写数据回送了几次
                    querytime: new Date().getTime(),
                    query_info: 1   //是否询问信息
                };
                obj = sock_obj();
            }
            else {
                obj.online = 1;
                obj.sock = socket; //保存socket
                if (obj.data != null) {
                    //调用发送函数
                    send2Sensor_write(obj.data);
                    //写回到界面显示
                    var vvtemp = {};
                    vvtemp.deviceid = v_deviceid;
                    if (obj.data.col_cycle != null) {
                        vvtemp.col_cycle = obj.data.col_cycle;
                    }
                    if (obj.data.warn_up != null) {
                        vvtemp.warn_up = obj.data.warn_up;
                    }
                    if (obj.data.warn_down != null) {
                        vvtemp.warn_down = obj.data.warn_down;
                    }
                    if (callback != null) {
                        callback(null, vvtemp);
                    }
                }
                var t2 = new Date().getTime();
                var t_diff = t2 - obj.querytime;
                if (t_diff > 1000 * 60 * 60 * 5) { //大于5个小时
                    obj.querytime = t2;
                    obj.query_info = 1;
                }
            }

            if (obj.query_info == 1) {
                console.log("want first read");
                obj.query_info = 0;
                send2sensor_ask(v_deviceid);
            }
           
            var v_time = new Date().Format('yyyy-MM-dd hh:mm:ss');
            var data_1 = null;
            var data_extern = null;
            data_1 = {
                temp: v_temp,
                deviceid: v_deviceid,
                press: v_press,
                time: v_time
            }

            if (v_extern != null) {
                data_extern = {
                    deviceid: v_deviceid,
                    col_cycle: v_extern.col_cycle,
                    signal : v_extern.signal,
                    vol: v_extern.vol,
                    press_unit: v_extern.press_unit
                    };
            }
            
            //console.log(data_1);
            //data_1 是数据,存储到数据库, data_extern是扩展数据
            if (callback != null)
                callback(data_1,data_extern);
        }
        function process_packet_cmd03(buff, pos, len) {
            console.log("receive the cmd 0x03,not ok");
            return 0;
        }
        function process_packet_cmd06(buff, pos, len) {
            //采集间隔时间上传返回
            var obj = sock_obj();
            if (obj != null) {
                obj.nwrite_ret++;
            }
            if (obj.nwrite_ret == obj.nwrite) { //所有指令返回，写成功
                obj.data = null;
                obj.nwrite = 0;
                obj.nwrite_ret = 0;
                console.log("指令返回成功");
            }
        }
        function process_packet_cmd10(buff, pos, len) {
            //上下限返回,报警手机返回
            var obj = sock_obj();
            if (obj != null) {
                obj.nwrite_ret++;
            }
            if (obj.nwrite_ret == obj.nwrite) {//所有指令返回，写成功
                obj.data = null;
                obj.nwrite = 0;
                obj.nwrite_ret = 0;
                console.log("指令返回成功");
            }
        }
        //采集周期
        function process_packet_cmd13(buff, pos, len) {
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var time = buff.readInt16BE(pos + 7);
            if (callback != null) {
               // console.log("%s采集时间 : %d",v_deviceid, time);
                callback(null,{ deviceid: v_deviceid, col_cycle: time });
            }
            return 0;
        }
        //69 00 01 00 01 23 02 00 02 C5 E7 16        //2=kpa压力单位 
        function process_packet_cmd23(buff, pos, len) {
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            let unit = buff.readInt16BE(pos + 7);
            //console.log("receive the unit is %d", unit);
            var unit_int = parseInt(unit);
            if (callback != null) {
                var unit_str = "pa";
                if (unit_int == 2)
                    unit_str = "Kpa";
                else if (unit_int == 3)
                    unit_str = "Mpa";
                //var unit_str = unit_int == 0 ? "pa" : "kpa";
                callback(null,{ deviceid: v_deviceid, press_unit: unit_str });
            }
            return 0;
        }
        //69 00 01 00 01 33 04 00 00 00 00 3A DA 16   //最小量程
        function process_packet_cmd33(buff, pos, len) {
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var lvalue = buff.readFloatBE(pos + 7);
            //console.log("最小量程:%d", lvalue);
            if (callback != null)
                callback(null,{ deviceid: v_deviceid, minvalue: lvalue });
            return 0;
        }
        //69 00 01 00 01 43 04 44 7A 00 00 0F F3 16   //最大量程
        function process_packet_cmd43(buff, pos, len) {
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var bvalue = buff.readFloatBE(pos + 7);
            //console.log("最大量程:%d", bvalue);
            if (callback != null)
                callback(null, { deviceid: v_deviceid, maxvalue: bvalue });
            return 0;
        }
        //69 00 01 00 01 53 04 00 00 00 00 3A DA 16   //报警下限 
        function process_packet_cmd53(buff, pos, len) {
            //config_read_sensor.down = buff.readInt32BE(pos + 7); 
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var value = buff.readFloatBE(pos + 7);
            //console.log("报警下限:%d", value);

            if (callback != null)
                callback(null, { deviceid: v_deviceid, warn_down: value });
            return 0;
        }
        //69 00 01 00 01 63 04 40 80 00 00 2E F2 16    //报警上限 
        function process_packet_cmd63(buff, pos, len) {
            //config_read_sensor.up = buff.readInt32BE(pos + 7);
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var value = buff.readFloatBE(pos + 7);
             //console.log("报警上限:%d", value);

            if (callback != null)
                callback(null, { deviceid: v_deviceid, warn_up: value });

            return 0;
        }
        //69 00 01 00 01 73 04 45 4E 40 00 7E 01 16    //回复指令 电池电压 
        function process_packet_cmd73(buff, pos, len) {
            //config_read_sensor.vol = buff.readInt32BE(pos + 7);
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var value = buff.readFloatBE(pos + 7)
             //console.log("电池电压:%d", value);

            if (callback != null)
                callback(null, { deviceid: v_deviceid, vol: value });

            return 0;
        }
        //69 00 01 00 01 83 06 15 31 92 63 76 00 35 3C 16//读取SIM 号码  
        function process_packet_cmd83(buff, pos, len) { //sim卡号码
            //six bytes
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var str = buf.toString('hex', pos + 7, pos + 7 + 6);
            if (str.length > 11)
                str = str.substring(0, 11);
            //console.log("电话号码:%s", str);


            if (callback != null)
                callback(null, { deviceid: v_deviceid, sim: str });

            return 0;
        }
        //69 00 01 00 01 93 02 00 00 44 26 16        //值0读取信号强度 
        function process_packet_cmd93(buff, pos, len) {//读取信号强度
            var v_deviceid = buff.toString('hex', pos + 1, pos + 5);
            var value = buff.readInt16BE(pos + 7);
            //console.log("信号强度:%d", value);
            if (callback != null)
                callback(null, { deviceid: v_deviceid, signal: value });
            return 0;
        }
        function process_packet_cmd(cmd, data, pos, len) {
            switch (cmd) {
                case 0x03:
                    break;
                case 0x04:
                    return process_packet_cmd04(data, pos, len);
                case 0x06:
                    return process_packet_cmd06(data, pos, len);
                case 0x10:
                    return process_packet_cmd10(data, pos, len);
                case 0x13:
                    return process_packet_cmd13(data, pos, len);
                case 0x23:
                    return process_packet_cmd23(data, pos, len);
                case 0x33:
                    return process_packet_cmd33(data, pos, len);
                case 0x43:
                    return process_packet_cmd43(data, pos, len);
                case 0x53:
                    return process_packet_cmd53(data, pos, len);
                case 0x63:
                    return process_packet_cmd63(data, pos, len);
                case 0x73:
                    return process_packet_cmd73(data, pos, len);
                case 0x83:
                    return process_packet_cmd83(data, pos, len);
                case 0x93:
                    return process_packet_cmd93(data, pos, len);
            }
        }
        function process_packet_print(buff, pos, len) {
            //const buftemp = Buffer.from(buff, pos, len);
            const buftemp = Buffer.allocUnsafe(len);
            buff.copy(buftemp, 0, pos, pos + len);
            //console.log(buftemp.toString('hex'));
        }
        function process_packet_1(data, startpos, len) {
            //存数据库
            // console.log("startend is %x %x", data[startpos], data[startpos + len - 1]);
            if (data[startpos] != 0x69 ) {
                console.log("error packet");
                return -1;
            }
            //console.log(data);
            //  console.log("the cmd is %d", data[startpos + 5]);
            var cmd = data[startpos + 5];
            process_packet_cmd(cmd, data, startpos, len);
        }
        function process_packet_compelete(buff) {
            //  console.log("process_packet_compelete %d", buf_datasize);
            var startpos = 0;
            var packet_len = 0;
            //var packet_len =  7 + 3 + buff[6+startpos];
            while (true) {
                if (buf_datasize >= 7) {
                    packet_len = 7 + 3 + buff[6 + startpos];
                    //console.log("packet_len %d", packet_len);
                }
                else {
                    //console.log("buf_datasize<7");
                    if (buf_datasize == 0)
                        return 0;
                    return startpos;
                }
                if (buf_datasize >= packet_len) {
                    //console.log("now buf_datasize %d packet_len %d startpos %d", buf_datasize, packet_len,startpos);
                    process_packet_1(buf, startpos, packet_len);
                    buf_datasize -= packet_len;
                    startpos += packet_len;

                }
                else {
                    if (buf_datasize == 0)
                        return 0;
                    return startpos;
                }
            }
        }
        //处理包
        function process_packet(data) {
            //把数据拷贝到buf之后
           // console.log("receive data :%d", data.length);
            data.copy(buf, buf_datasize);
            buf_datasize += data.length;
            //  console.log("now recv length " + buf_datasize);
            if (buf_datasize < 7) {//不够包头的长度，继续接收
                return;
            }
            var startpos = process_packet_compelete(buf);
            if (startpos != 0) {
                buf.copy(buf, 0, startpos, startpos + buf_datasize);
            }

        }
        socket.on('data', function (data) {
            process_packet(data);
        });
        socket.on('close', function () {
            //将id状态改为不在线
            console.log('close: ' + socket.remoteAddress + ' ' + socket.remotePort);
            device_offline();
            //var index = sockets.indexOf(socket);
            //sockets.splice(index, 1);
        });
        socket.on('error', function (err) {
            console.log('socket error:' + err);
            socket.end();
            device_offline();
        });
        socket.on('end', function () {
            console.log('client disconnected');
            device_offline();
        });
    });
    server.on('close', function () {
        console.log('Server closed');
    });

    server.listen(8051);

}



var option = null;
var option2 = null;
var url  = "http://192.168.1.232:9069/sensor_data/";
var url2 = "http://118.190.203.202:9069/sensor_data/";
function cb(ret,info){
    if(ret == 500)
        console.log("post error info:",info);
}

function callback(data, data_ext) {
    url += "8051";//port;
    url2 += "8051";
    if(option == null)
        option = server_post.parseurl(url);
    if (option2 == null)
        option2 = server_post.parseurl(url2);
    var rd = { data: data, data_ext: data_ext };
   // console.log(".");

   // server_post.post_data(rd, option, null, cb);
    server_post.post_data(rd, option2, null, cb);
}


function callback_udp(data) {
    var obj = JSON.parse(data);
    console.log("send to sensor:", obj);
    send2sensor_ask(obj.deiveid)
}
console.log("start the tcpserver");
ProcessTcpServer(callback);
console.log("start the udpserver");
udp.ProcessUdpServer(8051, callback_udp);


function test() {
    var min = 20;
    var max = 25;
    var deviceid = parseInt(Math.random() * (50 - 1 + 1) + 1, 10);
    deviceid += ""
    data = {
        temp: parseInt(Math.random() * (max - min + 1) + min, 10),
        deviceid: "00010001",
        press: parseInt(Math.random() * (50000 - 20000 + 1) + 50000, 10),
        time :new Date().Format('yyyy-MM-dd hh:mm:ss')
        //time: v_time
    };
    data_ext = {
        deviceid: "00010001",
        col_cycle: 10,
        signal: 12,
        vol: 13,
        press_unit: "pa"
    };
    callback(data, data_ext);
    setTimeout(test, 1000*10);
}
test();
//ProcessTcpServer(callback);
//exports.ProcessTcpServer = ProcessTcpServer;
// aaafun.aaa();
// exports.ProcessTcpServer = ProcessTcpServer;
// exports.send2Sensor_write0 = send2Sensor_write0;
// exports.send2sensor_ask = send2sensor_ask;

//ProcessTcpServer(null,null);

//function sendRead_info(flag, id, socket) {
//    console.log("read %s", flag);
//    var data = read_info[flag];
//    if (data == null) {
//        console.log("error!no flag of %s", flag);
//        return;
//    }
//    var buf_temp = Buffer.from(data);

//    setdeviceid(id, buf_temp);
//    setcrc16(buf_temp);
//    console.log("send data");
//    console.log(buf_temp);
//    socket.write(buf_temp);
//}

